package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author: liufh
 * @create: 2021-06-27 22:48
 **/
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void loadSqlXmlConfig(InputStream inputStream) throws DocumentException {
        //解析映射配置文件mapper.xml
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        List<Element> list = rootElement.selectNodes("//select|insert|update|delete");
        for (Element element : list) {
            MappedStatement mappedStatement = new MappedStatement();
            String id = element.attributeValue("id");
            mappedStatement.setId(id);
            mappedStatement.setParameterType(element.attributeValue("parameterType"));
            mappedStatement.setResultType(element.attributeValue("resultType"));
            mappedStatement.setSql(element.getTextTrim());
            mappedStatement.setType(element.getName().toUpperCase());
            String key = namespace + "." + id;
            configuration.getMappedStatementMap().put(key, mappedStatement);
        }
    }

}
